package com.tencent.cloud.iov.util.storage;

import android.text.TextUtils;

import com.tencent.mars.xlog.Log;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 缓存管理，用于临时数据的存储，格式为[<String, String>]，需持久化的数据请调用TXSharePreferencesUtils进行存储
 *
 * @author vinsonhuang
 * @date 2018/8/17
 */
public class TXCacheManager {

    private static final String TAG = TXCacheManager.class.getSimpleName();

    private Map<String, String> mCacheMap = new ConcurrentHashMap<>();

    private Map<String, OnCacheChangeListener> mCacheChangeListeners = new ConcurrentHashMap<>();

    private static TXCacheManager sInstance = new TXCacheManager();

    private TXCacheManager() {
    }

    public static TXCacheManager getInstance() {
        return sInstance;
    }

    public boolean containsKey(String key) {
        return mCacheMap.containsKey(key);
    }

    public void put(String key, String value) {
        mCacheMap.put(key, value);

        // 回调监听key的listener
        callbackListener(key, value);
    }

    public String get(String key) {
        return mCacheMap.get(key);
    }

    public void setMap(String key, Map<String, String> values) {
        if (null == values || values.isEmpty()) {
            return;
        }
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String> entry : values.entrySet()) {
            builder.append(entry.getKey()).append("=").append(entry
                    .getValue()).append("&");
        }
        put(key, builder.toString());
    }

    public Map<String, String> getMap(String key) {
        String value = get(key);
        if (TextUtils.isEmpty(value)) {
            return null;
        }

        String[] values = value.split("&");
        if (null != values && values.length > 0) {
            Map<String, String> map = new HashMap<>();
            for (String v : values) {
                String[] keyValue = v.split("=");
                if (null != keyValue && 2 == keyValue.length) {
                    map.put(keyValue[0], keyValue[1]);
                }
            }
            return map;
        }
        return null;
    }

    public void remove(String key) {
        if (!TextUtils.isEmpty(key)) {
            mCacheMap.remove(key);
        }
    }

    /**
     * 注册cache change 监听器
     *
     * @param key      要监听的key，若需要监听多个key，则格式为： key1;key2;.....keyn
     * @param listener 监听器
     */
    public boolean registerCacheChangeListener(String key, OnCacheChangeListener listener) {
        if (TextUtils.isEmpty(key) || null == listener) {
            Log.e(TAG, "register change listener failed, reason[%s]", "key is invalid");
            return false;
        }
        mCacheChangeListeners.put(key, listener);
        return true;
    }

    /**
     * 取消注册key
     *
     * @param key
     */
    public void unRegisterCacheChangeListener(String key) {
        if (!TextUtils.isEmpty(key) && mCacheChangeListeners.containsKey(key)) {
            mCacheChangeListeners.remove(key);
        }
    }

    /**
     * 清理内存，仅在应用登出时调用
     */
    public void clear() {
        if (null != mCacheMap) {
            mCacheMap.clear();
        }
        if (null != mCacheChangeListeners) {
            mCacheChangeListeners.clear();
        }
    }

    /**
     * cache change 监听器
     */
    public interface OnCacheChangeListener {

        /**
         * cache changed 回调接口
         *
         * @param key   修改的key
         * @param value 修改的value
         */
        void onCacheChanged(String key, String value);
    }

    private void callbackListener(String key, String value) {
        for (Map.Entry<String, OnCacheChangeListener> entry : mCacheChangeListeners.entrySet()) {
            if (entry.getKey().contains(key)) {
                entry.getValue().onCacheChanged(key, value);
            }
        }
    }
}
